package com.zqxq.lottery.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.zqxq.common.constant.Result;
import com.zqxq.common.utils.BigDecimalUtils;
import com.zqxq.common.utils.StrUtils;
import com.zqxq.lottery.api.alipay.AlipayNotityValidator;
import com.zqxq.lottery.api.feign.LotteryServerFeignClient;
import com.zqxq.lottery.entity.bo.order.TradeInfoBO;
import com.zqxq.lottery.entity.enums.ActivityIdEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.Map;

/**
 * @Description ：支付宝回调处理
 * @Author ： 解风
 * @Date ： 2018/03/21 11:19
 */
@Api(value = "支付宝回调API接口",tags = "支付宝回调API接口")
@Controller
@RequestMapping(value="/notify")
@Slf4j
public class NotifyController {

    @Autowired
    private LotteryServerFeignClient lotteryServerFeignClient;

    /**
     * 支付宝 异步回调地址
     * @param modelMap
     * @return
     */
    @ResponseBody
    @RequestMapping("/alipayNotity")
    @ApiOperation(value="支付宝 异步回调地址", notes="支付宝 异步回调地址")
    public String alipayNotity(HttpServletRequest request, ModelMap modelMap){
        Map<String,String> map= requestToMap(request);
        log.info("阿里支付回调数据："+map);
//        boolean bool = SignCheck.signCheck(map);
        boolean bool= AlipayNotityValidator.notityValidator(map);
        log.info("验签结果bool："+bool);
        if(bool){
            log.info("验签成功");
            String passback_params = map.get("passback_params");
            if(StrUtils.isEmpty(passback_params)){
                return "false";
            }
            long userId = 0;
            int type = 0;
            Long couponId = null; //优惠券id
            BigDecimal balance = BigDecimal.ZERO; //余额
            String trade_status = map.get("trade_status");
            String trade_no = map.get("trade_no");
            String buyer_id = map.get("buyer_id");
            String total_amount = map.get("total_amount");//支付金额
            String out_trade_no = map.get("out_trade_no");//订单号
            String refund_fee =  map.get("refund_fee");//退款额
            String receipt_amount = map.get("receipt_amount");//实收金额
            try {
                passback_params = URLDecoder.decode(passback_params, "utf-8");
                String[] arr = passback_params.split(",");
                type = Integer.parseInt(arr[0]);
                userId = Long.parseLong(arr[1]);
                if (StrUtils.isNotEmpty(arr[2]) && !"null".equals(arr[2].toLowerCase())){
                    couponId = Long.parseLong(arr[2]);
                }
                if (StrUtils.isNotEmpty(arr[3]) && !"null".equals(arr[3].toLowerCase())){
                    balance = new BigDecimal(arr[3]);
                }
                log.info("回调参数user_id={},trad_status={},total_amount={},out_trade_no={},refund_fee={},receipt_amount={}",userId,trade_status,total_amount,out_trade_no,refund_fee,receipt_amount);
                //保存回调参数
                TradeInfoBO bo = new TradeInfoBO();
                bo.setUserId(userId);
                bo.setTradeNo(trade_no);
                bo.setTradeWay(2);
                bo.setTradeType(type);
                bo.setOrderId(Long.parseLong(out_trade_no));
                bo.setResult(trade_status);
                bo.setData(JSONObject.toJSONString(map));
                Result rs1 = lotteryServerFeignClient.insertTradeInfo(bo);
                if(!rs1.success()){
                    return "false";
                }
                if("TRADE_SUCCESS".equals(trade_status) || "TRADE_FINISHED".equals(trade_status)){
                    //处理充值或者购买竞猜
                    if(type == 0){//充值
                        Result rs = lotteryServerFeignClient.recharge(userId, BigDecimalUtils.getBigDecimal(total_amount), 1, buyer_id, Long.parseLong(out_trade_no));
                        if(!rs.success()){
                            return "false";
                        }
                    } else if(type == 1){// 购买竞猜
                        Result rs = lotteryServerFeignClient.alipayConsume(userId, BigDecimalUtils.getBigDecimal(total_amount), Long.parseLong(out_trade_no), buyer_id,couponId,balance);
                        if(!rs.success()){
                            return "false";
                        }
                    }
                } else {
                    //交易失败
                }
            } catch (Exception e) {
                log.error("notify  alipayNotity is error", e);
                return "false";
            }

            return "success";
        }
        return "false";
    }

    private static Map<String, String> requestToMap(HttpServletRequest _request) {
        Map<String, String> map = new java.util.HashMap<String, String>();
        java.util.Enumeration<String> pns = _request.getParameterNames();
        while (pns.hasMoreElements()) {
            String s = pns.nextElement();
            map.put(s, _request.getParameter(s));
        }
        return map;
    }

}
